<?php

namespace Biz\model\salesRebate;

use Biz\model\salesRebate\SalesAccountLog as mSalesAccountLog;
use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\tools\Log;
use Medoo\Medoo;

class SalesAccount extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_sales_rebate';

    const _DATABASE_ = 'biz_sales_rebate';

    const _TABLE_NAME = 'sales_account';

    const TYPE_PERSONAL = 1;//个人账户
    const TYPE_COMPANY = 2;//公司账户
    const TYPE_APP = 3;//app内带货账户

    const STATUS_NORMAL = 0;
    const STATUS_DELETE = 9;

    const TYPE_TP_GROUP = [
        self::TYPE_PERSONAL,
        self::TYPE_COMPANY
    ];

    const USER_TYPE_DESC = [
        self::TYPE_PERSONAL => '节选-个人',
        self::TYPE_COMPANY  => '节选-公司',
        self::TYPE_APP      => 'APP-带货'
    ];

    public static function getAllByWhere($files = '*', $where = [])
    {
        $data = self::select($files, $where);
        return $data;
    }

    public static function getOneByWhere($files = '*', $where = [])
    {
        $data = self::get($files, $where);
        return $data;
    }

    public static function addData($data)
    {
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            throw new \Exception('数据库操作错误');
        }
        return true;
    }

    public static function getAccountInfosByUids($uids)
    {
        $accountList = self::select('*', [
            'uid'    => $uids,
            'status' => self::STATUS_NORMAL
        ]);
        $formatData = [];
        if ($accountList) {
            foreach ($accountList as $account) {
                $formatData[$account['uid']][$account['type']] = $account;
            }
        }
        return $formatData;
    }

    public static function getAccountInfosByUid($uid)
    {
        return self::select('*', [
            'uid' => $uid,
        ]);
    }

    public static function updateAccountInfo($info, $uid, $type)
    {
        self::update($info, [
            'uid'  => $uid,
            'type' => $type
        ]);
    }

    public static function addAccountInfo($info)
    {
        self::insert($info);
    }


    public static function getAccountListByFilter($filter, $limit)
    {
        if ($filter['uid']) {
            $uids = $filter['uid'];
            $total = 1;
        } else {
            $total = self::count([
                'type'  => $filter['type'],
                'GROUP' => ['uid']
            ]);
            $uids = self::select([
                'uid',
                'maxtime' => Medoo::raw('MAX(edittime)')
            ], [
                'type'  => $filter['type'],
                'GROUP' => 'uid',
                'ORDER' => ['maxtime' => 'DESC'],
                'LIMIT' => $limit
            ]);
            $uids = array_column($uids, 'uid');
        }
        $accountList = self::select('*', [
            'uid'   => $uids,
            'ORDER' => [
                'uid' => $uids,
                'type'
            ]
        ]);
        $formatData = [];
        if ($accountList) {
            foreach ($accountList as $account) {
                $formatData[$account['uid']]['types'][$account['type']] = $account;
                if ($account['status'] == self::STATUS_NORMAL) {
                    $formatData[$account['uid']]['valid'][$account['type']] = $account['type'];
                }
            }
        } else {
            $total = 0;
        }
        return [
            'list'  => $formatData,
            'total' => $total
        ];
    }


    /**
     * @param $uid 账户uid
     * @param $type 账户类型
     * @param $amount 返佣金额 或则 提现金额
     * @param $goodsAmount 商品销售金额
     * @param array $operateLog 操作日志log
     * @param $totalWithdrawalAmount 更改累计提现金额
     * @return bool
     * @throws \Exception
     */
    public static function updateAccount($accountInfo, $uid, $type, $amount, $goodsAmount, $operateLog, $totalWithdrawalAmount = 0)
    {
        $sourceData = [];
        $targetData = [];
        if ($accountInfo) {
            $data = [
                'balance' => bcadd($accountInfo['balance'], $amount, 2),
                'status'  => self::STATUS_NORMAL,
            ];
            $targetData = [
                'uid'     => $uid,
                'type'    => $type,
                'balance' => $data['balance'],
            ];
            if ($goodsAmount) {
                $data['sale_amount'] = bcadd($accountInfo['sale_amount'], $goodsAmount, 2);
                $targetData['sale_amount'] = $data['sale_amount'];
            }
            if ($totalWithdrawalAmount) {
                $data['total_withdrawal_amount'] = bcadd($accountInfo['total_withdrawal_amount'], $totalWithdrawalAmount, 2);
                $targetData['total_withdrawal_amount'] = $data['total_withdrawal_amount'];
            }
            $sourceData = [
                'uid'                     => $uid,
                'type'                    => $type,
                'balance'                 => $accountInfo['balance'],
                'sale_amount'             => $accountInfo['sale_amount'],
                'total_withdrawal_amount' => $accountInfo['total_withdrawal_amount']
            ];
            $ret = self::update($data, [
                'uid'  => $uid,
                'type' => $type
            ]);
        } else {
            $data = [
                'uid'         => $uid,
                'type'        => $type,
                'balance'     => $amount,
                'sale_amount' => $goodsAmount,
                'status'      => self::STATUS_NORMAL,
            ];
            $targetData = [
                'uid'         => $uid,
                'type'        => $type,
                'balance'     => $amount,
                'sale_amount' => $goodsAmount,
            ];
            $ret = self::insert($data);
        }
        if ($ret->errorCode() !== '00000') {
            throw new \Exception('数据库操作错误');
        }
        $data = [
            'uid'               => $uid,
            'type'              => $type,
            'amount'            => $amount,
            'operate_type'      => isset($operateLog['operate_type']) ? $operateLog['operate_type'] : 0,
            'withdrawal_code'   => isset($operateLog['withdrawal_code']) ? $operateLog['withdrawal_code'] : '',
            'receipt_number'    => isset($operateLog['receipt_number']) ? $operateLog['receipt_number'] : '',
            'operate_user_type' => isset($operateLog['operate_user_type']) ? $operateLog['operate_user_type'] : 0,
            'operate_user_id'   => isset($operateLog['operate_user_id']) ? $operateLog['operate_user_id'] : 0,
            'source_data'       => $sourceData ? json_encode($sourceData, JSON_UNESCAPED_UNICODE) : '',
            'target_data'       => $targetData ? json_encode($targetData, JSON_UNESCAPED_UNICODE) : '',
        ];
        Log::info('更改返佣账户信息log:' . json_encode($data, JSON_UNESCAPED_UNICODE));
        return mSalesAccountLog::addData($data);
    }

}